<?php

namespace app\common\business;

use app\common\model\mysql\SysLogininfor as SysLogininforModel;
use UAParser\Parser;

class SysLogininfor
{
    public $logininforObj = null;
    public function __construct()
    {
        $this->logininforObj = new SysLogininforModel();
    }

    //添加登录日志
    public function addLogininfor($msg = '',$user_name = '',$status = 0){
        // 获取User-Agent字符串
        $userAgent = request()->header('user-agent'); // 假设你已经在使用ThinkPHP 6
        // 创建解析器实例
        $parser = Parser::create();
        // 解析User-Agent
        $result = $parser->parse($userAgent);
        // 输出操作系统信息
        $os = $result->os->family; // 如 Windows, macOS, Android 等
        // 如果你想要更详细地处理版本信息（例如，仅当存在时才显示补丁号）
        $versionString = $result->os->major . "." . $result->os->minor;
        if ($result->os->patch !== null) {
            $versionString .= "." . $result->os->patch;
        }
        $osInfo = $os." ".$versionString;
        // 输出浏览器类型和版本
        // 如果需要判断是否为Chrome Mobile
        if($result->ua->family === 'Chrome Mobile' || ($result->ua->family === 'Chrome' && $result->device->family === 'Mobile')) {
            $browser = "Chrome Mobile";
            $browserInfo = $browser;
        }else{
            $browser = $result->ua->family; // 如 Chrome
            $browserVersion = $result->ua->major . "." . $result->ua->minor . "." . $result->ua->patch; // 如 10.0.0
            $browserInfo = $browser." ".$browserVersion;
        }

        $data = [
            'user_name'=>$user_name,
            'ipaddr'=>request()->ip(),
            'login_location'=>'XX XX',
            'browser'=>rtrim($browserInfo, '.') ,
            'os'=>rtrim($osInfo, '.') ,
            'status'=>$status,
            'msg'=>$msg,
            'login_time'=>date("Y-m-d H:i:s",time()),
        ];
        $this->logininforObj->addLogininfor($data);
        return true;
    }

    //查询登录日志
    public function getNormalLogininfor($where = [],$field = "*",$limit,$page,$order){
        $logininforData = $this->logininforObj->getNormalLogininforList($where,$field,$limit,$page,$order);
        if(!$logininforData){
            return [];
        }
        $logininforData = $logininforData->toArray();
        return $logininforData;
    }

    //根据$ids数组，删除数据库记录delete
    public function DellogininforIds($ids){
        $ids = explode(',', $ids);
        $result = $this->logininforObj->DellogininforIds($ids);
        return $result;
    }

    //清空操作日志表
    public function logininforCleanBus(){
        $result = $this->logininforObj->logininforCleanModel();
        return $result;
    }
}
